package com.kgc.easyshopping.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kgc.easyshopping.dao.AddressMapper;
import com.kgc.easyshopping.entity.Address;
import com.kgc.easyshopping.service.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Resource
    private AddressMapper addressMapper;

    @Override
    public PageInfo<Address> selectPageInfo(Map<String, Object> params) {
        int pageNum = (int) params.get("pageNum");
        int pageSize = (int) params.get("pageSize");
        PageHelper.startPage(pageNum,pageSize);
        List<Address> addresses = addressMapper.selectAll(params);
        return new PageInfo<Address>(addresses);
    }

    @Override
    public Address selectByPrimaryKey(String aid) {
        return addressMapper.selectByPrimaryKey(aid);
    }

    @Override
    public String insert(Address address) {
        String site = "";
        Map<String, Object> AddressMap = new HashMap<>();
        String userid = address.getUserid();
        if(userid!=null && userid!=""){
            AddressMap.put("userid",userid);
        }
        List<Address> list = addressMapper.selectAll(AddressMap);
        if(list.size()<=10){
            if(addressMapper.insertSelective(address)==1){
                site = "true";
            }else{
                site = "false";
            }
        }else{
            site = "已经添加了10个地址，不能再添加了！";
        }
        return site;
    }

    @Override
    public boolean deleteByPrimaryKey(String aid) {
        return addressMapper.deleteByPrimaryKey(aid)==1?true:false;
    }

    //改变地址默认值的状态
    @Override
    public boolean updateByPrimaryKeySelective(Address address) {
        Map<String, Object> map = new HashMap<>();
        String userid = address.getUserid();
        if(userid!=null && userid!=""){
            map.put("userid",userid);
        }
        List<Address> list = addressMapper.selectAll(map);
        for (Address address1:list){
            address1.setIsdefault(0);
            addressMapper.updateByPrimaryKeySelective(address1);
        }
        return addressMapper.updateByPrimaryKeySelective(address)==1?true:false;
    }

    //改变地址
    @Override
    public boolean updateAddress(Address address) {
        return addressMapper.updateByPrimaryKeySelective(address)==1?true:false;
    }
}
